﻿using Interface.Cache;
using Interface.Core.Utility;
using Interface.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Interface.Core.Controllers
{
    [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
    public class CoreController : Controller
    {
        public DataContext db = null;
        public string appid = null;
        private string token = null;
        private string timestamp = null;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Length == 0)
            {
                appid = Request.QueryString["appid"];
                token = Request.QueryString["token"];
                timestamp = Request.QueryString["timestamp"];

                if (!CredentialUtility.Validate(appid, token, timestamp))
                {
                    string result = ResultUtility.FailureResult("不合法的凭证!" + Request.Url);

                    filterContext.Result = Content(result); return;
                }
            }

            base.OnActionExecuting(filterContext);

            db = new DataContext();
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            db.Dispose(); db = null;
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            if (db != null) { db.Rollback(); db.Dispose(); db = null; }

            LogHelper.Error(filterContext.Controller, filterContext.Exception);

            string result = ResultUtility.FailureResult("系统错误!");

            filterContext.Result = Content(result);
        }

        [HttpGet]
        public string TokenTest()
        {
            return ResultUtility.SuccessResult("token test.");
        }

        [AllowAnonymous]
        [HttpGet]
        public string RemoveCache(string key)
        {
            string message = string.Empty;

            if (CommonCache.ExistsCache(key))
            {
                CommonCache.RemoveCache(key);

                message = "cache is removed.";
            }
            else { message = "the kye is not exists."; }

            return ResultUtility.SuccessResult(message);
        }
    }
}